<template>
	<view>
		<view class="message-list">
			<view class="message-item" v-for="(item, index) in messageList" :key="index">
				<view class="right" v-if="item.from === 'b'">
					<text>{{item.message}}</text>
					<up-avatar size="25" src="https://uview-plus.jiangruyi.com/h5/static/uview/album/6.jpg"></up-avatar>
				</view>
				<view class="left" v-else>
					<up-avatar size="25" src="https://uview-plus.jiangruyi.com/h5/static/uview/album/5.jpg"></up-avatar>
					<text>{{item.message}}</text>
				</view>
			</view>
		</view>

		<view class="send-model">
			<up-icon name="photo"></up-icon>
			<up-input class="input-model" placeholder="请输入内容" border="surround" v-model="message"></up-input>
			<view class="right-icon">
				<text class="send-btn" @click="doSend">发送</text>
				<up-icon name="plus-circle"></up-icon>
				<up-icon name="camera"></up-icon>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import io from '@hyoga/uni-socket.io';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	const message = ref('')
	const socket = ref('')
	const messageList = ref([])
	const doConnect = () => {
		socket.value = io('http://localhost:3001', {
			path: '/socket',
			query: {
				userId: 'b'
			},
			transports: ['websocket', 'polling'],
			timeout: 5000,
		});
		socket.value.on('connect', () => {
			console.log('加入聊天室成功')
			socket.value.on('reciveMessage', (obj) => {
				messageList.value.push(obj)
			})
		})
	}
	// 发消息：1. 私发：给某人单独发 2.群发：我要给聊天室里的每一个人都要发消息
	onLoad((options) => {
		doConnect()
	})
	const doSend = () => {
		const messageItem = {from: 'b', message: message.value,to: 'bin'}
		socket.value.emit('send', messageItem)
		messageList.value.push(messageItem)
		console.log(message.value)
	}
	// const doConnect = () => {
	// 	socket.on('connect', () => {
	// 		console.log('连接成功')
	// 	})
	// }
	// doConnect()
</script>

<style lang="scss" scoped>
	.send-model {
		position: fixed;
		bottom: 0;
		width: 100%;
		box-sizing: border-box;
		height: 150rpx;
		display: flex;
		align-items: center;
		padding: 0 20rpx;

		.input-model {
			margin: 0 20rpx;
		}

		.right-icon {
			display: flex;
			align-items: center;
			flex-wrap: nowrap;
		}
	}
	.send-btn{
		background: #2491F8;
		padding: 10rpx;
	}
	.left{
		display: flex;
		justify-content: flex-start;
	}
	.right{
		display: flex;
		justify-content: flex-end;
	}
</style>